package com.application.mestory;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.application.mestory.dao.StoryDao;
import com.application.mestory.entity.MeStory;
import com.application.mestory.entity.MeStoryObject;
import com.application.mestory.jaxb.Story;
import com.application.mestory.jaxb.StoryObject;
import com.application.mestory.mapper.MeStoryToStory;
import com.application.mestory.mapper.StoryToMeStory;

@Controller
public class RestController {

	private static final Logger logger = LoggerFactory
			.getLogger(RestController.class);
	@Autowired
	private StoryDao storyDao;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/rest/load", method = RequestMethod.GET, produces = "application/xml")
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Story load() {
		logger.info("execute load()");

		List<MeStory> stories = storyDao.load();
		
		return MeStoryToStory.map(stories.get(0));
	}
	@RequestMapping(value = "/rest/save", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public void saveMyStory(@RequestBody Story story) {
		logger.info("execute save()");

		MeStory meStory = StoryToMeStory.map(story);
		meStory.setName("Auto Story");
		storyDao.save(meStory);
		
		logger.info(meStory.getId() + ": " + meStory.getName() + " saved.");
	}
	
	@RequestMapping(value = "/rest/test", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public String test() {
		logger.info("execute test");
		
		MeStory story = new MeStory();
		story.setId(1);
		story.setName("test2");
		MeStoryObject storyObject = new MeStoryObject();
		storyObject.setId(5);
		storyObject.setHeight(10);
		storyObject.setImageName("stoA");
		storyObject.setLeft(20);
		storyObject.setTop(30);
		storyObject.setWidth(40);
		List<MeStoryObject> storyObjects = new ArrayList<MeStoryObject>();
		storyObjects.add(storyObject);
		storyObject = new MeStoryObject();
		storyObject.setId(6);
		storyObject.setHeight(11);
		storyObject.setImageName("stoB");
		storyObject.setLeft(22);
		storyObject.setTop(31);
		storyObject.setWidth(41);
		storyObjects.add(storyObject);
		story.setMeStoryObjects(storyObjects);

		storyDao.save(story);
		logger.info("test - created");
		return "test";

		
	}
}
